//
//  BaseNetworkUtil.m
//  MapArgiculture
//
//  Created by xiongguobing on 2018/5/29.
//  Copyright © 2018年 xiongguobing. All rights reserved.
//

#import "BaseNetworkUtil.h"
#import "AFNetworking.h"

@implementation BaseModel



@end


@interface BaseNetworkUtil ()
@property (nonatomic, strong)NSURLSessionDataTask *currentTask;
@property (nonatomic, strong)AFHTTPSessionManager *manager;
@end

@implementation BaseNetworkUtil



static id instance = nil;
+ (instancetype)sharedInstance {
    return [[self alloc] init];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

- (instancetype)init {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super init];
    });
    return instance;
}

- (void)getWithModuleURLStr:(NSString *)urlString
                 parameters:(NSDictionary *)parameters
                    success:(success)success
                    failure:(failure)failure
                    withHud:(BOOL)hud
{
    [self requestWithURLString:urlString parameters:parameters method:@"GET" success:success failure:failure isBody:NO isHud:hud];
}

- (void)postWithModuleURLStr:(NSString *)urlString
                  parameters:(NSDictionary *)parameters
                     success:(success)success
                     failure:(failure)failure
                     withHud:(BOOL)hud
{
    [self requestWithURLString:urlString parameters:parameters method:@"POST" success:success failure:failure isBody:NO isHud:hud];
}

- (void)requestWithURLString: (NSString *)URLString
                  parameters: (NSDictionary *)parameters
                      method: (NSString *)method
                     success:(success)success
                     failure:(failure)failure
                      isBody:(BOOL)isBody
{
    [self requestWithURLString:URLString parameters:parameters method:method success:success failure:failure isBody:isBody isHud:NO];
}

- (void)requestWithURLString: (NSString *)URLString
                  parameters: (NSDictionary *)parameters
                      method: (NSString *)method
                     success:(success)success
                     failure:(failure)failure
                      isBody:(BOOL)isBody
                       isHud:(BOOL)isHud
{
    [self requestWithURLString:URLString parameters:parameters method:method success:success failure:failure isBody:isBody isHud:isHud isShowError:YES];
}

- (void)postWithModuleURLStr:(NSString *)urlString
                  parameters:(NSDictionary *)parameters
                     success:(success)success
                     failure:(failure)failure
                 isShowError:(BOOL)isShowError
{
    [self requestWithURLString:urlString parameters:parameters method:@"POST" success:success failure:failure isBody:NO isHud:NO isShowError:NO];
}

- (void)requestWithURLString: (NSString *)URLString
                  parameters: (NSDictionary *)parameters
                      method: (NSString *)method
                     success:(success)success
                     failure:(failure)failure
                      isBody:(BOOL)isBody
                       isHud:(BOOL)isHud
                 isShowError:(BOOL)isShowError
{
    //申明返回的结果是json类型
    if (isBody) {
        self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }else{
        self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    }
    //添加项目配置依赖
    [self.manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"from"];
    [self.manager.requestSerializer setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"];
    NSString * version = [NSString stringWithFormat:@"%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    [self.manager.requestSerializer setValue:version forHTTPHeaderField:@"version"];
    //默认超时时间
    self.manager.requestSerializer.timeoutInterval = 15;
    
    if (isHud) {
        [HUDUtil show];
    }
    NSString * token = [[NSUserDefaults standardUserDefaults] objectForKey:KToken];
    if (token.length) {
        NSLog(@"token = %@", token);
        [self.manager.requestSerializer setValue:token forHTTPHeaderField:@"_gt"];
    }
    if (![URLString hasPrefix:@"http"]) {
        URLString = Append2Str(BaseURL, URLString);
    }
    if ([method isEqualToString:@"GET"]) {
        //调用AFN框架的方法
        //默认有一个菊花在转动
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
        });
        
        /**
         *  请求超时的时间
         */
        
        [self.manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [HUDUtil dismiss];
            //默认有一个菊花在转动
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
            //如果请求成功，则回调responseObject
            NSLog(@"GET请求成功 URL= %@ \nparameters = %@ \nresponseObject = %@",URLString,parameters,responseObject);
            if (success) {
                success(responseObject);
            }
            if (isShowError && [[responseObject objectForKey:@"code"] integerValue] != networkSuccessStatus) {
                kShowWithString(responseObject[@"message"]);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [HUDUtil dismiss];
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
            //如果请求失败，控制台打印错误信息
            NSLog(@"%@",error);
            if (failure) {
                failure(error);
            }
            if (isShowError) {
                kShowWithString(error.localizedDescription);
            }
        }];
    }
    
    if ([method isEqualToString:@"POST"]) {
        //默认有一个菊花在转动
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
        });
        [self.manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [HUDUtil dismiss];
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
            NSLog(@"POST请求成功 URL= %@ \nparameters = %@ \nresponseObject = %@",URLString,parameters,responseObject);
            if (success) {
                success(responseObject);
            }
            if (isShowError && [[responseObject objectForKey:@"code"] integerValue] != networkSuccessStatus) {
                kShowWithString(responseObject[@"message"]);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [HUDUtil dismiss];
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
            NSLog(@"%@",error);
            if (failure) {
                failure(error);
            }
            if (isShowError) {
                kShowWithString(error.localizedDescription);
            }
        }];
    }
}

+ (NSString *)getNetworkType
{
    UIApplication *app = [UIApplication sharedApplication];
    id statusBar = [app valueForKeyPath:@"statusBar"];
    NSString *network = @"";
    
    if (KIsiPhoneX) {
        //        刘海屏
        id statusBarView = [statusBar valueForKeyPath:@"statusBar"];
        UIView *foregroundView = [statusBarView valueForKeyPath:@"foregroundView"];
        
        NSArray *subviews = [[foregroundView subviews][2] subviews];
        
        for (id subview in subviews) {
            if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarWifiSignalView")]) {
                network = @"WIFI";
            }else if ([subview isKindOfClass:NSClassFromString(@"_UIStatusBarStringView")]) {
                network = [subview valueForKeyPath:@"originalText"];
            }
        }
    }else {
        //        非刘海屏
        UIView *foregroundView = [statusBar valueForKeyPath:@"foregroundView"];
        NSArray *subviews = [foregroundView subviews];
        
        for (id subview in subviews) {
            if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
                int networkType = [[subview valueForKeyPath:@"dataNetworkType"] intValue];
                switch (networkType) {
                    case 0:
                        network = @"NONE";
                        break;
                    case 1:
                        network = @"2G";
                        break;
                    case 2:
                        network = @"3G";
                        break;
                    case 3:
                        network = @"4G";
                        break;
                    case 5:
                        network = @"WIFI";
                        break;
                    default:
                        break;
                }
            }
        }
    }
    
    if ([network isEqualToString:@""]) {
        network = @"unknown";
    }
    return network;
}

- (void)downloadWithUrl:(NSString *)url path:(NSString *)path downloadSuccess:(downloadSuccess)success failure:(failure)failure
{
    NSURLSessionDownloadTask * task = [self.manager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"进度%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:path];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (error) {
            NSLog(@"error is %@", error);
            if (failure) {
                failure(error);
            }
        }else{
            if (success) {
                success(response);
                NSLog(@"down load success, filepath %@", filePath);                
            }
        }
    }];
    [task resume];
}

#pragma mark - setter and getter
- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
        _manager.responseSerializer = [AFJSONResponseSerializer serializer];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects: @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/xml",@"text/plain",nil];
    }
    return _manager;
}

@end
